

from flask import current_app
from flask import g
from flask import render_template
from flask import session

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.modules.index import blue_url
from info.utils.common import user_logo_data


@blue_url.route("/")
@user_logo_data
def index():
    """
    显示首页
    1. 如果用户已经登录，将当前登录用户的数据传到模板中，供模板显示
    :return:
    # """
    # user_id=session.get('user_id',None)
    # user=''
    # if user_id:
    #     try:
    #         user=User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user=g.user
    news_list=[]

    try:
        news_list =  News.query.filter().order_by(News.clicks.desc()).limit(constants.HOME_PAGE_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())

    category_li=[]

    categorys= Category.query.all()
    for cate in categorys:
        category_li.append(cate.to_dict())

    data = {
        'user': user.to_dict() if user else  None,
        'click_news_list' :click_news_list,
        'category_li':category_li
    }

    return render_template('news/index.html',data=data  ,click_news_list=click_news_list)

@blue_url.route("/favicon.ico")
def get_favion():
    return current_app.send_static_file('news/favicon.ico')